<script setup lang="ts">
import { onMounted, ref } from "vue";
import { ClSelect } from "@chulei-ui/components";
import { Container } from "typedi";
import { useDebounceFn } from "@vueuse/core";
import { AuthService } from "../../repositories/AuthService";
import { emitter } from "../../bus";
import type { Select, SelectInstance } from "@chulei-ui/components";

import type { AuthRole } from "../../repositories/role/entity";
const playerId = defineModel<number | number[]>();
const authService = Container.get(AuthService);

const selectRef = ref<SelectInstance<AuthRole>>();
const refresh = async () => {
  const items = await authService.getAuthRoles();
  return items.map((role) => {
    return {
      label: role.name,
      data: role,
      value: role.id,
    } as Select.Item<AuthRole>;
  });
};

const debounceRefresh = useDebounceFn(() => {
  selectRef.value!.refresh();
}, 50);

onMounted(() => {
  emitter.on("auth-success", debounceRefresh);
});
defineOptions({
  name: "AuthRoleSelect",
});
</script>

<template>
  <cl-select
    ref="selectRef"
    v-bind="{ ...$attrs, ...$props }"
    v-model="playerId"
    :actions="['refresh']"
    filterable
    :placeholder="`请选择角色`"
    :items="refresh"
    clearable
  >
    <template #default="{ options }">
      <el-option v-for="option in options" :key="option.value" :label="option.label" :value="option.value" />
    </template>
  </cl-select>
</template>

<style scoped lang="scss"></style>
